/**
 * 扑克牌生成器
 * @public
 * */
module.exports = class PokerGenerator {
    /**
     * 洗牌的数量
     * 52（张排除大小王）
     * 54（张为整副扑克牌）
     * @param {Number} shuffle_num
     * @public
     * */
    constructor (shuffle_num) {
        this._shuffle_num = shuffle_num;
        this._shuffle_cards = [];
    }

    /**
     * 洗牌
     * @public
     * */
    shuffle () {
        // 1、抽牌法
        let shuffle_pick = function (m) {
            //生成m张牌
            let arr = new Array(m);
            for (let i = 0; i < m; i++) {
                arr[i] = i;
            }
            // 每次抽出一张牌，放在另一堆。把最后一张未抽的牌放在空位子上。
            let cards = [];
            for (let i = m; i > 0;) {
                let rnd = Math.floor(Math.random() * i);
                cards.push(arr[rnd]);
                arr[rnd] = arr[--i];
            }
            return cards;
        };

        // 2、插牌法
        let shuffle_insert = function (m) {
            //每次生成一张最大的牌，与随机的某张牌换位子
            let arr = new Array(m);
            arr[0] = 0;
            for (let i = 1; i < m; i++) {
                let rnd = Math.floor(Math.random() * (i + 1));
                arr[i] = arr[rnd];
                arr[rnd] = i;
            }
            return arr;
        };

        // 3、换牌法
        let shuffle_swap = function (m) {
            //生成m张牌
            let arr = new Array(m);
            for (let i = 0; i < m; i++) {
                arr[i] = i;
            }
            //第i张与任意一张牌换位子，换完一轮即可
            for (let i = 0; i < m; i++) {
                let rnd = Math.floor(Math.random() * (i + 1)),
                    temp = arr[rnd];
                arr[rnd] = arr[i];
                arr[i] = temp;
            }
            return arr;
        };

        // 从3中洗牌方式中随机一种进行洗牌
        let shuffle_functions = [];
        shuffle_functions.push(shuffle_pick);
        shuffle_functions.push(shuffle_insert);
        shuffle_functions.push(shuffle_swap);
        let execute_function = shuffle_functions[Math.floor(Math.random() * 3)];
        this._shuffle_cards = [];
        this._shuffle_cards = execute_function(this._shuffle_num);
    }

    /**
     * 发牌
     * @param {Number} card_num 发牌数量
     * @public
     * */
    dealCards (card_num) {
        let cards = [];
        for (let i = 0; i < card_num; i++) {
            cards.push(this._shuffle_cards.shift());
        }
        return cards;
    }

    /**
     * 获得扑克牌对象
     * @param {Number} card_id
     * @public
     * */
    getCardConfig (card_id) {
        if (card_id < 0 || card_id >= 54) {
            console.error('获得扑克牌对象配置失败！' + card_id);
        }
        let color = Math.floor(card_id / 13);
        let value = card_id % 13;
        return {
            id: card_id,
            value: value,
            color: color,
            sort: 13 - value,
            point: value > 9 ? 0.5 : value + 1,
            des: ['黑桃', '红桃', '梅花', '方块'][color] + ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'][value]
        };
    }
};